<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/7
 * Time: 11:22
 */
namespace app\wechat\controller;
use app\models\Bases;

class Pay extends Base{
    protected  $user_info;
    protected  $openid;
    public function __construct(){
        parent::__construct();
        $openid = cookie("openid");
        $this->openid = $openid;
        $this->user_info = self::getUserInfo("openid = '{$openid}'",'');
    }

    public function pay1(){
        $pay = new \app\service\Pay(99,20,'牛股宝','',$this->user_info['nickname'],$this->user_info['username'],0,1,$this->openid);
        //当用户点击购买时，通知用户下单
       /* $message = new Message();
        //$name = '钱时代', $operation = 1, $money, $openId
        $message_result = $message->sendMessage($this->user_info['nickname'],1,300,$this->openid);*/

        $param   = $pay->payParam(); //获取参数
        $signMsg = $pay->signMsg();  //生成加密串
        //保存订单编号
        $order_log = new Bases('order_log');
        $order_log->insertData(['order_no' => $param['orderNo'],'create_time'=>time()]);
        return view('pay1',['param'=>$param,'signMsg'=>$signMsg]);
    }

    public function pay2(){
        $pay = new \app\service\Pay(99,20,'新股道','',$this->user_info['nickname'],$this->user_info['username'],0,2,$this->openid);
        $param   = $pay->payParam(); //获取参数
        $signMsg = $pay->signMsg();  //生成加密串
        return view('pay2',['param'=>$param,'signMsg'=>$signMsg]);
    }

    public function pay3(){
        $pay = new \app\service\Pay(99,20,'牛模王','',$this->user_info['nickname'],$this->user_info['username'],0,3,$this->openid);
        $param   = $pay->payParam(); //获取参数
        $signMsg = $pay->signMsg();  //生成加密串
        return view('pay3',['param'=>$param,'signMsg'=>$signMsg]);
    }

    public function signMsg(){
        $input = input('param.');
        $pay = new \app\service\Pay($input['pay_type'],$input['pay_money'],'控股王','',$this->user_info['nickname'],$this->user_info['username'],0,1);
        $signMsg = $pay->signMsg();  //生成加密串
        return json(self::formatSuccessResult($signMsg));
    }

    public function paySuccess(){
        $pay_result  = $_REQUEST;
        $pay_name  = explode(',',$pay_result['ext1']);
        return view('paySuccess',['result'=>$pay_result,'pay_name'=>$pay_name]);

    }

    public function notify(){
        $userModel = new Bases('user');
        $orderModel = new Bases('order');
        $productModel = new Bases('product');
        $order_log = new Bases('order_log');
        $payInfo = $_REQUEST;
        $payInfo['openid'] = $payInfo['ext2'];
        $payInfo['user_info'] = self::getUserInfo("openid = '{$payInfo['openid']}'",'');
        $userInfo = self::getUserInfo("openid = '{$payInfo['openid']}'",'');
        $arr = json_encode($payInfo,true);
        $order_log->insertData(['text' => $arr,'create_time'=>time()]);
        $product_id = substr($payInfo['ext1'], -1, 1);//产品的id
        $orderInfo = $orderModel->find("order_no = '{$payInfo['orderNo']}' ");
        if($orderInfo){
            return ;
        }
        //$orderOne = $orderModel->find("uid = ".$userInfo['uid'].' and status = 2');
        $order = $orderModel->selectData("uid = ".$userInfo['uid'].' and status = 2','',' order_id desc');
        $productOne = $productModel->find('product_id = '.$product_id);
        if(!empty($order)){
            //查詢上一條訂單信息
            if($order[0]['expiration_time'] >= time()){
                //還沒過期
                $addOrder['effective_time']  = $order[0]['expiration_time'];//生效時間為上賬訂單的過期時間
                $addOrder['expiration_time'] = $order[0]['expiration_time'] + $productOne['duration'];//過期時間 = 上個定單的過期時間 + 產品的時長
            }else{
                //過期了
                $addOrder['expiration_time'] = strtotime(date('Y-m-d'.'00:00:00',time())) + 24*3600 + $productOne['duration'];// 過期時間 = 今天的時間戳開始時間 +一天+產品時長
                $addOrder['effective_time'] = time();//生效时间
            }
        }else{//之前沒有訂單
            $addOrder['expiration_time'] = strtotime(date('Y-m-d'.'00:00:00',time())) + 24*3600*2-1 + $productOne['duration'];// 過期時間 = 今天的時間戳開始時間 +一天+產品時長
            $addOrder['effective_time'] = time();//生效时间
        }
        if($payInfo['payResult'] == 1){
            $addOrder['status'] = 2;
        }else{
            $addOrder['status'] = 1;
        }
        $addOrder['money'] = $payInfo['orderAmount']/100;//价格
        $addOrder['pay_time'] = strtotime($payInfo['payDatetime']);//支付时间
        $addOrder['create_time'] = time();
        $addOrder['order_no'] = $payInfo['orderNo'];//訂單編號
        $addOrder['product_id'] = $product_id;//产品的id
        $addOrder['uid'] = $userInfo['uid'];
        $addOrder['type'] = 2;//微信支付
        $rs = $orderModel->insertData($addOrder);
        if($rs){
            $order_id = $userInfo['order_id'];
            if(!empty($order_id)){
                $order = $orderModel->find('order_id ='.$order_id);
                if(!empty($order) && $order['expiration_time'] <= time()){//有訂單信息並且過期了
                    $data['order_id'] = $rs;
                    $data['uid'] = $userInfo['uid'];
                    $userModel->updateData($data);//跟新用户order_id
                }
            }else{
                $data['order_id'] = $rs;
                $data['uid'] = $userInfo['uid'];
                $userModel->updateData($data);//跟新用户order_id
            }
        }
/*        $arr = json_encode($payInfo,true);
        $order_log->insertData(['text' => $arr,'create_time'=>time()]);*/
        //{
                                //"payDatetime":"20170413142522",
                                //"signType":"1",
                                //"version":"v1.0",
                                //"issuerId":"",
                                //"orderNo":"20170413022451291679",
                                //"payResult":"1",
                                //"mchtOrderId":"201704131424534116",
                                //"ext1":"\u725b\u80a1\u5b9d",
                                //"ext2":"",
                                //"orderAmount":"20",
                                //"signMsg":"T2uLNX5qc6mV\/cQfCKXznl10Cumk7cNVlZl8MdDSvrJ2rsdFbzDyxX8la9aPdOGhWZ+8Cw4WsIHChVEsuzCN1N0VTrX2mOlF3MpsXKcAgL9RDZ8uO7IlGG+6PNzjdhDYplB7HkNwJiSRrPO4\/mN5exYD4P5SxN9blMBHsgpt1u14o0q7lRz+txJYjsRkzYd5V5bRG+c4me+9xuavw9WLDNckQfbZjNMpBbedUuGSyFDagZcEi8E8yK\/BvEIu1n9IanBwJQFSl+MAq91gg9JRMAOzW1lIZVbjirDf2IqLhDiqot\/y6dGgZFr\/Gq+Jrls2+J2a9VG2i7qlsPQZMw\/Ulg==",
                                //"payType":"99",
                                //"merchantId":"105840170321008",
                                //"language":"1",
                                //"orderDatetime":"20170413022451"
                                //}

    }

    public function test(){
        $time = strtotime("20170413142522");
        $str = '{"payDatetime":"20170413140216","signType":"1","version":"v1.0","issuerId":"","orderNo":"20170413020147236714","payResult":"1","mchtOrderId":"201704131401490468","ext1":"\u725b\u80a1\u5b9d,1","ext2":"","orderAmount":"20","signMsg":"QH\/i9OipoBs5wcjV+NTVIBuwtwB5GyHj2Y46rLgY8MSei5JE+AtwGiT9IS\/dIQxjOUTZwfd9qchXP2vDOpp5FKx2vSagIc8uRfeoNCjaC1LzbqbdTO4DFbvJXeZBEucWGWsGLfhSD4lN62rdKBVOxaTPwDzrdhhIT1+FiYM9MPblDvKCgfPngjOXJZYYG7XvnmGfoxBbmt7+43iR4AubfWL09PjqDAxuciDnstgMZ72poT7Jy8BedQj0bW7MKtAVNWkpoKSq\/2MwTs9uYiLJ63UrR0Drq\/a\/I8efo8IWtYajhHuagTg1SyzOIOsMu2bQsAdTFvgaM0LO0oRWH3EWFA==","payType":"99","merchantId":"105840170321008","language":"1","orderDatetime":"20170413020147"}';
        echo '<pre>';
        print_r($time);
        print_r(json_decode($str));
    }
}